//
//  ILCarDetailViewController.m
//  ILife
//
//  Created by lanou on 15/10/27.
//  Copyright © 2015年 ILife. All rights reserved.
//

#import "ILCarDetailViewController.h"
#import "FMDatabase.h"


@interface ILCarDetailViewController ()<UIWebViewDelegate, UIScrollViewDelegate>

@property (nonatomic, strong) UILabel *collectLabel;
@property (nonatomic, strong) UIButton *collectButton;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) UIButton *shareButton;
@property (nonatomic, strong) UILabel *shareLabel;
@property (nonatomic, strong) FMDatabase *dataBase;
@property (nonatomic, assign) BOOL isCollection;
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, assign) CGFloat contentY; // 偏移
@property (nonatomic, strong) NSMutableArray *resourceLocArr;


@end

@implementation ILCarDetailViewController

- (NSMutableArray *)resourceLocArr {
    if (!_resourceLocArr) {
        self.resourceLocArr = [NSMutableArray array];
    }
    return _resourceLocArr;
}

- (void)requestData {
    NSString *str = [[GET_DETAIL_URL_STRING stringByAppendingString:self.collectionModel.resourceLoc] stringByAppendingString:@".html"];
    NSString *HTMLstring = [[NSString alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:str]] encoding:(NSUTF8StringEncoding)];
    _webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    [_webView loadHTMLString:HTMLstring baseURL:nil];
    _webView.delegate = self;
    _webView.scrollView.delegate = self;
    _webView.scrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_webView];
  
}

- (void)back:(UIBarButtonItem *)leftBarButton {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:(UIBarButtonItemStyleBordered) target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem = leftBarButton;
    // Do any additional setup after loading the view.
    [self requestData];
    self.isHidden = YES;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"collect"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] style:(UIBarButtonItemStylePlain) target:self action:@selector(collectAndShare)];
    // 创建打开数据库
    _dataBase = [FMDatabase databaseWithPath:CARCOLLECTIONFILEPATH];
    if ([_dataBase open]) {
        NSLog(@"数据库打开成功");
       [_dataBase executeUpdate:@"CREATE TABLE ICARCOLLEC (resourceLoc text, picUrl text, title text)"];
        
    } else {
        NSLog(@"数据库打开失败");
    }
    
    FMResultSet *resultSet = [_dataBase executeQueryWithFormat:@"SELECT * FROM ICARCOLLEC"];
    while ([resultSet next]) {
        NSString *resourceLoc = [resultSet stringForColumn:@"resourceLoc"];
        if ([self.collectionModel.resourceLoc isEqualToString:resourceLoc]) {
            self.isCollection = YES;
            [self.navigationItem.rightBarButtonItem setImage:[UIImage imageNamed:@"collected"]];
            break; // 如果相同则 停止
        } else {
            self.isCollection = NO;
        }
    }
    [resultSet close];
    
}

- (void)collectAndShare {
    if (_isCollection == NO) {
        [_dataBase executeUpdate:@"INSERT INTO ICARCOLLEC (resourceLoc, picUrl, title) values (?,?,?)",self.collectionModel.resourceLoc,self.collectionModel.picUrl,self.collectionModel.title];
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"收藏成功" preferredStyle:(UIAlertControllerStyleAlert)];
        [self presentViewController:alertController animated:YES completion:nil];
        [self.navigationItem.rightBarButtonItem setImage:[UIImage imageNamed:@"collected"]];
        self.isCollection = YES;
    } else {
        [self.navigationItem.rightBarButtonItem setImage:[UIImage imageNamed:@"collected"]];
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"收藏了,换一个吧" preferredStyle:(UIAlertControllerStyleAlert)];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(dismiss) userInfo:nil repeats:NO];

}
- (void)dismiss {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    CGFloat webHeight = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"] floatValue];
    webView.scrollView.contentSize = CGSizeMake(0, webHeight);
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (_webView.scrollView.contentOffset.y >= 24) {
        self.navigationController.navigationBar.hidden = YES;
    }
    _webView.frame = CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT - 20);
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    // 向上滑 导航栏出现
    CGFloat y = _webView.scrollView.contentOffset.y;
    CGFloat reduce = y - _contentY;
    _contentY = y;
    if (reduce < 0) {
        self.navigationController.navigationBar.hidden = NO;
    }
// 滑动到底部导航栏出现
    if (y == _webView.scrollView.contentSize.height - SCREEN_HEIGHT  + 69) {
        self.navigationController.navigationBar.hidden = NO;
    }
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
    

  
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
